<?php

namespace App\Http\Controllers\Bap;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Currency;
use App\Models\Property;
use App\Models\Order;
use App\Models\Entrust;
use Exception;
use DB;

/**
 * 委托单.
 */
class EntrustController extends Controller
{
    /**
     * 获取所有币种信息.
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function currency_types(Request $request)
    {
        $data = Currency::where([
            'online_switch' => 1,
        ])->where('is_standard', '<>', 1)->orderBy('orderby')->select('id', 'name_en')->get();

        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $data]);
    }

    /**
     * 交易单（买入卖出）.
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function order_list(Request $request)
    {
        try {
            $data = [];
            $uid = $request->get('uid'); //用户id
            $cid = $request->get('cid'); //币种id
            $type = $request->get('type'); //类型 1买入 2卖出
            if (empty($uid) || empty($cid)) {
                throw new Exception(1003);
            }
            //用户资产信息
            $porperty = Property::where(['cid' => $cid, 'uid' => $uid])
            ->select('balance', 'blocked')->first();
            //买5（价格从高到低）
            $buys = Order::where(['cid' => $cid, 'uid' => $uid, 'type' => 5])
                ->orderBy('price', 'desc')
                ->limit(5)
                ->select('price', 'num')
                ->get();
            //卖5（价格从低到高）
            $sells = Order::where(['cid' => $cid, 'uid' => $uid, 'type' => 6])
                ->orderBy('price', 'desc')
                ->limit(5)
                ->select('price', 'num')
                ->get();

            $data['property'] = $porperty;
            $data['buys'] = $buys;
            $data['sells'] = $sells;

            return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $data]);

        } catch (Exception $e) {
            $msg = $e->getMessage();
            return respF($msg);
        }
    }

    /**
     * 委托单列表
     *
     * @ author: zrc
     * @ E-mail:904725327@qq.com
     * @ date: 2018/4/8
     * @access public|private|protected
     * @param  mixed    name    comment
     * @param  int    name    comment
     * @param  string    name    comment
     * @param  bool       name    comment
     * @param  array   name    comment
     * @return void|int|string|boolean|array        comment
     */
    public function entrust_list(Request $request)
    {
        $data = [];
        $uid = $request->get('uid'); //用户id
        $type = $request->get('type') ?? 3; //类型 1未成交 2 已撤销 3 已成交

        if (empty($uid)) {
            return respF(1003);
        }

        $entrusts = Entrust::where(function ($query) use ($uid) {
            if (!empty($uid)) {
                $query->where('uid', $uid);
            }
        })
        ->where(function ($query) use ($type) {
            switch ($type) {
                case 1:
                    $query->whereIn('status', [1, 2]);
                    break;
                case 2:
                    $query->whereIn('status', [4, 5]);
                    break;
                case 3:
                    $query->whereIn('status', [2, 3]);
                    break;
            }
        })->orderBy('id', 'desc')->paginate(5);

        $all = Entrust::where(function ($query) use ($uid) {
                    if (!empty($uid)) {
                        $query->where('uid', $uid);
                    }
                })
                ->where(function ($query) use ($type) {
                    switch ($type) {
                        case 1:
                            $query->whereIn('status', [1, 2]);
                            break;
                        case 2:
                            $query->whereIn('status', [4, 5]);
                            break;
                        case 3:
                            $query->whereIn('status', [2, 3]);
                            break;
                    }
                })->orderBy('id', 'desc')->get();

        if (!$entrusts) {
            return respF(1009);
        }
        $data['count'] = count($all);
        $data['list']= [];
        foreach ($entrusts  as $k => $v) {
            $data['list'][$k]['id'] = $v->id;
            $data['list'][$k]['price'] = $v->price;
            $data['list'][$k]['num'] = $v->num;
            $data['list'][$k]['deal'] = $v->deal;
            $data['list'][$k]['no_deal'] = sprintf("%.8f", ($v->num - $v->deal));
            $data['list'][$k]['status'] = $v->status;
            $data['list'][$k]['c_name'] = $v->currency->name_en;
            $data['list'][$k]['type'] = $v->type;
            $data['list'][$k]['created_at'] = date("Y-m-d H:i:s", $v->deal_time);
            if(empty($v->deal_time)) {
                $data[$k]['created_at'] = $v->created_at->format('Y-m-d H:i:s');
            }
        }

        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $data]);
    }

    /**
     * 取消委托
     *
     * @param Request $request
     *
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function entrust_undo(Request $request)
    {
        $info = $request->all();
        if (empty($info['id'])) {
            return respF(1019);
        }
        $infos = Entrust::where('id', $info['id'])->whereIn('status', [1,2])->first();
        if ($infos) {
            $currency = $infos->currency->buy_fee;
            if (!empty((float)$infos->deal)) {//部分取消
                $data['status'] = 4;
            } else {//全部取消
                $data['status'] = 5;
            }
            if ($infos->type==3) {
                $money = bcmul($infos->num-$infos->deal, $infos->price, 8)+bcmul($infos->num-$infos->deal, bcmul($infos->price/100, $currency, 8), 8);
                $where['uid'] = $infos->uid;
                $map['is_standard'] = 1;
                $map['pay_switch'] = 1;
                $map['buy_switch'] = 1;
                $where['cid'] = Currency::where($map)->first(['id'])->id;
            } else {
                $money = $infos->num-$infos->deal;
                $where['uid'] = $infos->uid;
                $where['cid'] = $infos->cid;
            }
            try {
                //开启事务
                DB::beginTransaction();
                $infos->update($data);
                Property::where($where)->increment('balance', $money);
                Property::where($where)->decrement('blocked', $money);
                DB::commit();
                return response()->json(['msg'=>'操作成功','status'=>1]);
            } catch (Exception $e) {
                DB::rollback();
                return respF(1020);
            }
        }
        return respF(1006);
    }


    /**
     * 买卖盘和最新交易
     *
     * @ author: zrc
     * @ E-mail:904725327@qq.com
     * @ date: 2018/4/8
     * @access public|private|protected
     * @param  mixed    name    comment
     * @param  int    name    comment
     * @param  string    name    comment
     * @param  bool       name    comment
     * @param  array   name    comment
     * @return void|int|string|boolean|array        comment
     */
    public function transactions(Request $request)
    {
        $info = $request->all();

        if (!empty($info['cid'])) {
            $cid = $info['cid'];
        } else {
            return respF(1006);

        }
        //买入数据
        $where['cid'] = $cid;
        $where['type'] = 3;
        $infos = Entrust::where($where)->whereIn('status', [1, 2])->orderBy('price', 'desc')
            ->take(5)->get(['price', 'deal', 'num']);
        //无数据时
        $arr = [
            '0' => ['price' => 0, 'y_num' => 0],
            '1' => ['price' => 0, 'y_num' => 0],
            '2' => ['price' => 0, 'y_num' => 0],
            '3' => ['price' => 0, 'y_num' => 0],
            '4' => ['price' => 0, 'y_num' => 0],
        ];
        $arr1 = [
            '0' => ['price' => 0, 'y_num' => 0],
            '1' => ['price' => 0, 'y_num' => 0],
            '2' => ['price' => 0, 'y_num' => 0],
            '3' => ['price' => 0, 'y_num' => 0],
            '4' => ['price' => 0, 'y_num' => 0],
        ];
        if (collect($infos)->count() < 1) {
            $list['buy'] = $arr;
        } else {
            foreach ($infos as $k => $v) {
                $list['buy'][$k]['price'] = number_format($v->price, 2,'.','');
                $list['buy'][$k]['y_num'] = number_format($v->num - $v->deal, 4,'.','');
            }
            switch (count($list['buy'])) {
                case 1:
                    unset($arr[0]);
                    $list['buy'] = array_merge($list['buy'], $arr);
                    break;
                case 2:
                    unset($arr[0]);
                    unset($arr[1]);
                    $list['buy'] = array_merge($list['buy'], $arr);
                    break;
                case 3:
                    unset($arr[0]);
                    unset($arr[1]);
                    unset($arr[2]);
                    $list['buy'] = array_merge($list['buy'], $arr);
                    break;
                case 4:
                    unset($arr[0]);
                    unset($arr[1]);
                    unset($arr[2]);
                    unset($arr[3]);
                    $list['buy'] = array_merge($list['buy'], $arr);
                    break;
                case 5:
                    break;
            }
        }
        //卖出数据
        $where1['cid'] = $cid;
        $where1['type'] = 4;
        $infos3 = Entrust::where($where1)->whereIn('status', [1, 2])->orderBy('price', 'asc')
            ->take(5)->get(['price', 'deal', 'num']);
        if (collect($infos3)->count() < 1) {
            $list['sell'] = $arr1;
        } else {
            foreach ($infos3 as $k => $v) {
                $list['sell'][$k]['price'] = number_format($v->price, 2,'.','');
                $list['sell'][$k]['y_num'] = number_format($v->num - $v->deal, 4,'.','');
            }
            $list['sell'] = array_reverse($list['sell']);
            switch (count($list['sell'])) {
                case 1:
                    unset($arr1[0]);
                    $list['sell'] = array_merge($arr1,$list['sell']);
                    break;
                case 2:
                    unset($arr1[0]);
                    unset($arr1[1]);
                    $list['sell'] = array_merge($arr1,$list['sell']);
                    break;
                case 3:
                    unset($arr1[0]);
                    unset($arr1[1]);
                    unset($arr1[2]);
                    $list['sell'] = array_merge($arr1,$list['sell']);
                    break;
                case 4:
                    unset($arr1[0]);
                    unset($arr1[1]);
                    unset($arr1[2]);
                    unset($arr1[3]);
                    $list['sell'] = array_merge($arr1,$list['sell']);
                    break;
                case 5:
                    break;
            }
        }

        //最新交易
        $trading = Order::where('cid',$cid)->orderBy('id','desc')->take(20)->get(['price','type','num','total_price']);
        
        if ($trading->count() > 1) {
            $list['trading'] = array_reverse($trading->toArray());
        } else {
            $list['trading'] = array();
        }
        $list['name_en'] = Currency::where('id',$cid)->value('name_en');
        $data['status'] = 1;
        $data['msg'] = '成功';
        $data['list'] = $list;
        
        return response()->json($data);
    }
}
